<template>

<div class="common-layout">
    <el-container>
      <el-aside width="500px">

        <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="姓名" prop="name" >
        <el-input v-model="ruleForm.name" disabled />
      </el-form-item>

      <el-form-item label="部门" prop="region">
        <el-select v-model="ruleForm.depentmentId" placeholder="请选择部门" disabled>
        <el-option label="IT信息部" :value="1" />
        <el-option label="人力资源部" :value="2" />
        <el-option label="财务部" :value="3" />
        <el-option label="销售部" :value="4" />
        <el-option label="行政部" :value="5" />
        </el-select>
      </el-form-item>
     
      
      <el-form-item label="请假类别" prop="type" >
        <el-radio-group v-model="ruleForm.leaveType" disabled>
          <el-radio :value="101" name="type">事假</el-radio>
          <el-radio :value="102" name="type">病假</el-radio>
          <el-radio :value="103" name="type">婚假</el-radio>
          <el-radio :value="104" name="type">丧假</el-radio>
          <el-radio :value="105" name="type">产假</el-radio>
          <el-radio :value="106" name="type">补休</el-radio>
          <el-radio :value="107" name="type">工伤</el-radio>
          <el-radio :value="108" name="type">其他</el-radio>
        </el-radio-group>
      </el-form-item>


     
      <el-form-item label="请假时间" prop="resource" >
  <!-- 开始时间 -->
  <div class="time-section">
    <span class="time-label">自</span>
    <el-date-picker
      v-model="ruleForm.startData"
      type="datetime"
      placeholder="开始时间"
      @change="calculateDuration"
      disabled
    />
  </div>

  <!-- 结束时间 -->
  <div class="time-section">
    <span class="time-label">至</span>
    <el-date-picker
      v-model="ruleForm.endData"
      type="datetime"
      placeholder="结束时间"
      disabled
      @change="calculateDuration"
    />
  </div>

  <!-- 统计信息 -->
  <div class="duration-info" disabled>
    共计 {{  ruleForm.totalDays }} 天 {{  ruleForm.totalHours }} 时
  </div>

  <!-- 新增的报到时间 -->
  <div class="time-section" style="margin-top: 12px"> <!-- 增加上边距 -->
    <span class="time-label">报到: 自</span>
    <el-date-picker
    disabled
      v-model="ruleForm.startData" 
      type="datetime"
      placeholder="报到时间"
    />
  </div>
</el-form-item>

      <el-form-item label="请假事由" prop="desc">
        <el-input v-model="ruleForm.reason" type="textarea" disabled/>
      </el-form-item>

      <el-form-item label="审核" prop="desc" >
        <el-radio-group   v-model="Approver.ApprovaStatus">
          <el-radio value="通过" name="type">通过</el-radio>
          <el-radio value="拒绝" name="type">拒绝</el-radio>
        </el-radio-group>
        <el-input v-model="Approver.remark" v-show="Approver.ApprovaStatus=='拒绝'" placeholder="原因"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="AddApprover()">
          提交
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>

      </el-aside>
      <el-main style="margin-left: 200px;">

      <!-- <el-table :data="tableStop"  style="width:500px">
    <el-table-column prop="approverName" label="审批人" width="150px" />
    <el-table-column prop="approvalStatus" label="状态"  width="150px"  >
      <template height="50px" v-slot="scope">
          <p v-if="scope.row.approvalStatus==101" >待审批</p>
          <p v-if="scope.row.approvalStatus==102" >审批中</p>
          <p v-if="scope.row.approvalStatus==103" >已通过</p>
          <p v-if="scope.row.approvalStatus==104" >已拒绝</p>

    </template>
  </el-table-column>

    <el-table-column prop="leaveRember" label="原因"  width="200px"  >
      <template v-slot="scope">

<p >{{scope.row.leaveRember}}</p>
    </template>
    </el-table-column>
  </el-table>  -->
 
  <el-table :data="tableStop2"  style="width:500px">
        <el-table-column prop="approverName" label="审批人" width="150px" />
        <el-table-column prop="approvaStatus" label="状态"  width="150px" />
        <el-table-column prop="remark" label="原因"  width="200px" />
      </el-table> 

      </el-main>
    </el-container>
  </div>


  </template>
  
  <script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted,reactive} from 'vue';
  import { ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
  import axios from 'axios'
  import {useRouter,useRoute} from 'vue-router'
import {useCounterStore} from '@/stores/counter'
let router=useRouter();
let route=useRoute();
let Store=useCounterStore();
  interface RuleForm {
    leaveId:number
    name: string
    depentmentId: string
    leaveType: string
    startData: string
    endData: string
    totalDays: number
    totalHours: number
    reason: string
    approvalStatus: string
    depName:string
  }
  
  const tableStop2=ref([]);
    const page2=reactive({
        DepenmentId:Store.CurrLoginUser.depenmentId,
        LeaveApplicationId:route.query.id
    })


  onMounted(()=>{
    shangjisn();
    })
  const shangjisn=()=>{
  axios({
    url:'http://localhost:5284/api/Level/QueryAppro',
    method:'get',
    params:page2
  })
  .then(res=>{
    console.log('查看审批状态数据',page)
    if(res.data.list!=null){
        console.log(res)
      tableStop2.value=res.data.list;
    }
  })
}



  const formSize = ref<ComponentSize>('default')
  const ruleFormRef = ref<FormInstance>()
  const ruleForm = reactive({
    leaveId:0,
    name: '',
    depentmentId: 0,
    leaveType: '',
    startData: '',
    endData: '',
    totalDays:0,
    totalHours:0,
    reason: '',
    approvalStatus: '',
    depName:""
  })
//审批记录表所需数据
const Approver=reactive<any>({
  leaveApplicationId:0,
  depenmentId:0,
  approverId:Store.CurrLoginUser.userId,
  approverName:Store.CurrLoginUser.UserName,
  approveLevel:Store.CurrLoginUser.levelId,
  approvaStatus:'',
  remark:""
})


const AddApprover=()=>{
  if(Approver.ApprovaStatus=='拒绝'){
    if(Approver.remark==""){
    ElMessage.error("原因必填");
    return
  }
  }
  
  console.log('请假申请id',Approver)
  axios({
    url:'http://localhost:5272/api/Leave/AddAppRova',
    method:'post',
    data:Approver
  })
  .then(res=>{
    if(res.data.code==101){
      console.log('请假申请id',ruleForm.leaveId)
      ElMessage.success("审批已完成")
      router.push({
        name:"LeaveShow",
        query:{
          id:page.LeaveId,
        }
      })  
    }
    else {
      ElMessage.error("审批失败")
    }
  })
}
//变量
const tableStop=ref([]);
const tablepost=ref([])
const page=reactive({
  DepId:Store.CurrLoginUser.depenmentId,
  LeaveId:route.query.id,
  LevelRoleId:Store.CurrLoginUser.levelId

})






onMounted(()=>{
  console.log('传输的id',route.query.id)
  getLevelList();
  shangji();
})

const getLevelList=()=>{
  axios({
    url:'http://localhost:5284/api/Level/GetLevelId',
    method:'get',
    params:{
      LeaveId:route.query.id
    }
  })
  .then(res=>{
    if(res.data.code==101){
      console.log('查询出的数据',res.data);
      ruleForm.leaveId=res.data.data.leaveId
      ruleForm.name=res.data.data.name
      ruleForm.depentmentId=res.data.data.depentmentId
      ruleForm.leaveType=res.data.data.leaveType
      ruleForm.startData=res.data.data.startData
      ruleForm.endData=res.data.data.endData
      ruleForm.totalDays=res.data.data.totalDays
      ruleForm.totalHours=res.data.data.totalHours
      ruleForm.reason=res.data.data.reason
      ruleForm.approvalStatus=res.data.data.approvalStatus
      ruleForm.depName=res.data.data.depName
      Approver.leaveApplicationId=res.data.data.leaveId
      Approver.depenmentId=res.data.data.depentmentId
    }
  })
}
const shangpo=reactive({

})

const shangji=()=>{
  axios({
    url:'http://localhost:5284/api/Level/QueryShangji',
    method:'get',
    params:page
  })
  .then(res=>{
    if(res.data.data!=null){
      tableStop.value=res.data.data;
    }
  })
}




//计算时间
  // const calculateDuration = () => {
  //     if (ruleForm.startData && ruleForm.endData) {
  //       const start = new Date(ruleForm.startData);
  //       const end = new Date(ruleForm.endData);
  //       const diff = end - start; // 时间差，单位毫秒
  //       const totalHours = diff / (1000 * 60 * 60); // 转换为小时
  //       ruleForm.totalDays = Math.floor(totalHours / 8); // 计算天数
  //       ruleForm.totalHours = totalHours % 8; // 计算剩余小时数
  //     }
  //   };

// 定义工作时间范围（假设每天工作时间为 9:00 - 18:00）
const WORK_START_HOUR = 9;
const WORK_END_HOUR = 18;
const WORK_HOURS_PER_DAY = 8; // 每天工作 8 小时

// 计算请假时间与工作时间的交集
const calculateWorkHours = (start: Date, end: Date) => {
  const startHour = start.getHours();
  const endHour = end.getHours();

  // 如果请假时间完全在工作时间之外，返回 0
  if (endHour < WORK_START_HOUR || startHour >= WORK_END_HOUR) {
    return 0;
  }

  // 计算当天的实际工作时间
  const workStart = new Date(start);
  workStart.setHours(WORK_START_HOUR, 0, 0, 0); // 当天工作开始时间
  const workEnd = new Date(start);
  workEnd.setHours(WORK_END_HOUR, 0, 0, 0); // 当天工作结束时间

  // 计算请假时间与工作时间的交集
  const overlapStart = start > workStart ? start : workStart;
  const overlapEnd = end < workEnd ? end : workEnd;

  // 返回交集的小时数
  return (overlapEnd - overlapStart) / (1000 * 60 * 60);
};

// 计算总请假时间
const calculateDuration = () => {
  if (!ruleForm.startData || !ruleForm.endData) {
    ruleForm.totalDays = 0;
    ruleForm.totalHours = 0;
    return;
  }

  const start = new Date(ruleForm.startData);
  const end = new Date(ruleForm.endData);

  if (end < start) {
    ElMessage.error("结束时间不能早于开始时间");
    ruleForm.totalDays = 0;
    ruleForm.totalHours = 0;
    return;
  }

  let totalWorkHours = 0;

  // 按天拆分请假时间
  let currentDayStart = new Date(start);
  while (currentDayStart < end) {
    const currentDayEnd = new Date(currentDayStart);
    currentDayEnd.setHours(23, 59, 59, 999); // 当天结束时间

    // 计算当天的工作时间
    const dayWorkHours = calculateWorkHours(
      currentDayStart < start ? start : currentDayStart,
      currentDayEnd > end ? end : currentDayEnd
    );

    totalWorkHours += dayWorkHours;

    // 移动到下一天
    currentDayStart = new Date(currentDayEnd);
    currentDayStart.setDate(currentDayStart.getDate() + 1);
    currentDayStart.setHours(0, 0, 0, 0);
  }

  // 按 8 小时为一天进行转换
  ruleForm.totalDays = Math.floor(totalWorkHours / WORK_HOURS_PER_DAY);
  ruleForm.totalHours = totalWorkHours % WORK_HOURS_PER_DAY-1;
};




const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
  }))
  </script>
<style scoped>
.time-section {
  margin-bottom: 12px;
  margin-left: 5px;
}

.time-label {
  margin-right: 8px;
  min-width: 28px;
  display: inline-block;
}

.duration-info {
  margin: 8px 0 12px 5px;
  color: #409eff;
  font-size: 14px;
}

:deep(.el-form-item__content) {
  display: block !important;
}

/* 响应式处理 */
@media (max-width: 768px) {
  .el-date-picker {
    width: 100% !important;
  }
  
  .time-label {
    margin-bottom: 4px;
    display: block;
  }
}

</style>
<style scoped>
.leave-apply-container {
  padding: 20px;
}
</style>
  